<?php

namespace Iwester\Http\Model\Book;

use Iwester\Http\Model\Base;
use Illuminate\Database\Eloquent\SoftDeletes;
use Iwester\Http\Model\Config\SiteConfig;
use Iwester\Http\Model\User\User;

class Book extends Base
{
    protected $table = 'books';
    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * Note that when '*' is set to true, this allows all unspecified fields to
     * be mass assigned. For security purposes, it is advised to set '*' to false
     * (or remove it), and explicitly make individual fields accessible as needed.
     *
     * @var array
     */
    protected $_accessible = [
        '*' => true,
        'id' => false
    ];

    protected $appends = ['seo'];

    public static $pubWith = ['author', 'category', 'firstChapter', 'lastChapter'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'keywords', 'img', 'book_author_id', 'book_category_id', 'first_chapter_id', 'last_chapter_id', 'last_update_time', 'book_description',
        'serial_status', 'book_words_num', 'view_count', 'is_vip', 'source', 'issued_time', 'qd_source', 'score'
    ];


    /**
     * 获取书籍
     * @param array $whereArr 筛选条件
     * @param array $orderBy 排序条件
     * @param int $pageSize 每页数量
     * @param int $pageType 是否分页
     * @return Article[]|\Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Collection
     */
    public static function getBookData($withArr = [], $whereArr = [], $orderBy = [['id' => 'desc']], $pageSize = 10, $paginate = true, $inArr = [])
    {
        if (!$withArr) $withArr = self::$pubWith;
        $query = Book::with($withArr);
        if ($whereArr) $query->where($whereArr);
        if ($inArr) $query->whereIn($inArr[0], $inArr[1]);
        if ($orderBy) {
            foreach ($orderBy as $column => $type) {
                if (is_array($type)) {
                    foreach ($type as $columnSub => $typeSub) {
                        $query->orderBy($columnSub, $typeSub);
                    }
                } else {
                    $query->orderBy($column, $type);
                }
            }
        }
        if ($paginate) {
            return $query->paginate($pageSize);
        } else {
            return $query->limit($pageSize)->get();
        }
    }

    /**
     * 关联书籍作者
     * @return mixed
     */
    public function author()
    {
        return $this->hasOne(BookAuthor::class, 'id', 'book_author_id');
    }

    /**
     * 关联书籍分类
     * @return mixed
     */
    public function category()
    {
        return $this->hasOne(BookCategory::class, 'id', 'book_category_id');
    }

    /**
     * 关联文章首篇
     * @return mixed
     */
    public function firstChapter()
    {
        return $this->hasOne(BookChapter::class, 'id', 'first_chapter_id');
    }

    /**
     * 关联文章尾篇
     * @return mixed
     */
    public function lastChapter()
    {
        return $this->hasOne(BookChapter::class, 'id', 'last_chapter_id');
    }

    /**
     * @param string $field
     * @param string $unit
     * @return string
     */
    public function formatNumber($field, $unit = '')
    {
        try {
            if (is_numeric($field)) {
                $number = $field;
            } else {
                $number = $this->$field;
            }
            if (empty($number) || !is_numeric($number)) return $number;
            if ($number > 10000 and $number < 100000000) {
                $leftNumber  = floor($number / 10000);
                $rightNumber = round(($number % 10000) / 10000, 2);
                $number      = floatval($leftNumber + $rightNumber);
                $number      = $number . '万';
            } else if ($number > 100000000) {
                $leftNumber  = floor($number / 100000000);
                $rightNumber = round(($number % 100000000) / 100000000, 2);
                $number      = floatval($leftNumber + $rightNumber);
                $number      = $number . '亿';
            } else {
                $decimals = $number > 1 ? 2 : 6;
                $number   = (float)number_format($number, $decimals, '.', '');
            }
            return (string)$number . $unit;
        } catch (Exception $exception) {
            return rand(1, 1000);
        }
    }

    public function getSerialStatuse()
    {
        try {
            if ($this->serial_status == 1) {
                return '已完本';
            } else {
                return '连载中';
            }
        } catch (Exception $exception) {
            return '连载中';
        }
    }

    /**
     * [章节]
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function chapter()
    {
        return $this->hasMany(BookChapter::class, 'book_id', 'id')
            ->orderBy('id', 'asc');
    }
}
